package com.crm.jdy.controller.wxmessage;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crm.jdy.common.pojo.UserInfo;
import com.crm.jdy.common.utils.api.ResultVo;
import com.crm.jdy.service.usermanager.RolePermissService;
import com.crm.jdy.service.usermanager.UserInfoService;
import com.crm.jdy.service.usermanager.WxService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;


@Slf4j
@Api(tags = "WxMessage", description = "微信环境配置")
@RestController
@Controller
public class WxController {

    @Reference(version = "${service.version}", check = false)
    UserInfoService userInfoService;

    @Autowired
    WxMpService wxMpService;

    @Autowired
    private RestTemplate restTemplate;

    @Reference(version = "${service.version}", check = false)
    WxService wxService;

    private Logger logger = LoggerFactory.getLogger(WxController.class);
    private static final String TOKEN = "tokens";

    /**
     * 微信验证token
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping(value = "/checkToken",produces = "text/html;charset=utf-8")
    public String checkToken(@RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp,
                             @RequestParam("nonce") String nonce, @RequestParam("echostr") String echostr) {
        //排序
        String[] arr = {TOKEN, timestamp, nonce};
        Arrays.sort(arr);

        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }

        //sha1Hex 加密
        MessageDigest md = null;
        String temp = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(content.toString().getBytes());
            temp = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if ((temp.toLowerCase()).equals(signature)){
            return echostr;
        }
        return null;
    }

    private static String byteToStr(byte[] byteArray){
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    private static String byteToHexStr(byte mByte){
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A','B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4)& 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }


//    登录的界面获取openID
    @RequestMapping("index")
    public ModelAndView cartList(HttpServletRequest request,HttpServletResponse response){
        Map<String, String> res = new HashMap<String, String>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, value);
                //如果字段的值为空，判断若值为空，则删除这个字段>
                if (null == res.get(en) || "".equals(res.get(en))) {
                    res.remove(en);
                }
            }
        }
        String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxaeda779a371ee311&secret=07a52865d2ce2640a167f8d7378c1da7&code="+res.get("code")+"&grant_type=authorization_code";
        ResponseEntity<String> results = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        String json = results.getBody();
        Map map = getMap(json);
        ModelAndView  modelAndView =new ModelAndView();
        modelAndView.addObject("openid",map.get("openid"));
        modelAndView.setViewName("index");
        return modelAndView;
    }


    //    修改用户的信息
    @RequestMapping("updateUser")
    public ResultVo updateUser(@ApiParam(value = "userInfo", required = true)
                             @NotNull @RequestBody UserInfo userInfo){
         Boolean bool =  userInfoService.updateInfo(userInfo);
        return ResultVo.success(bool);
    }

    public static Map getMap(String path){
        Map map = new LinkedHashMap();
        try {
            map = JSONObject.parseObject(path, LinkedHashMap.class);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @GetMapping("/tokens")
    public String uploadheadimg(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        System.out.println("----------------验证微信服务号信息开始----------");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            System.out.println("----验证服务号结束.........");
            return echostr;
        } else {
            return null;
        }
    }


    @GetMapping("/sentMessges")
    public void sentMessges(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

        RestTemplate restTemplate=new RestTemplate();
        Map<String,String> params=new HashMap<>();
        params.put("appid","wxaeda779a371ee311");
        params.put("secret","07a52865d2ce2640a167f8d7378c1da7");
        ResponseEntity<Object> responseEntity = restTemplate.getForEntity("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}",Object.class,params);
        System.out.println(responseEntity);
        System.out.println("==================");
        WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
        System.out.println("==========----========");
        templateMessage.setTemplateId("QHZWiYSdF7IdbFtM_c9KroEmSjRYPXuPv4-LFVhQh0Y");
        templateMessage.setToUser("oVHFO6bJn6TwOLVlF-1_s0H86Mx0");
        System.out.println("===2222222222222=======");
        List<WxMpTemplateData> data = new ArrayList();
        data.add( new WxMpTemplateData("first", "亲，请记得收货。"));
        data.add( new WxMpTemplateData("keyword", "xinxi"));
        data.add( new WxMpTemplateData("keyword1", "2020-12-02"));
        data.add( new WxMpTemplateData("remark", "亲，欢迎再次光临。"));
        System.out.println("======333344444==========");
        templateMessage.setData(data);
        System.out.println("=======555555555=======");
        try {
            System.out.println("======888888888=====");
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        }catch ( Exception e) {
            log.error("【微信模版消息】发送失败, {}", e);
        }
    }


}
